package com.example.hotelsystem.service.impl;

import code.CodeError;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hotelsystem.entity.Role;
import com.example.hotelsystem.entity.User;
import com.example.hotelsystem.entity.UserRole;
import com.example.hotelsystem.mapper.UserMapper;
import com.example.hotelsystem.page.Pagesize;
import com.example.hotelsystem.pdf.Product;
import com.example.hotelsystem.pdf.ViewPDF;
import com.example.hotelsystem.result.Result;
import com.example.hotelsystem.server.Server;
import com.example.hotelsystem.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hotelsystem.utils.ExcelUtils;
import com.example.hotelsystem.utils.UUIDGenrateUtil;
import com.example.hotelsystem.vo.user.UserSearchVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Indexed;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lee
 * @since 2020-10-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService UserRoleService;

    @Autowired
    BirthdayService birthdayService;

    @Autowired
    RoleService roleService;

    @Autowired
    TDictService tDictService;

    public User getSexText(User user){
        if(user.getSex()==null){
            return user;
        }
       user.setSexText(tDictService.getDictText(user.getSex(),"hotelSex"));

        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertUser(User user){
        if(user.getUsername()==null||user.getUsername()==""){
            return Result.error("请填写用户名");
        }
        if(user.getPassword()==null||user.getUsername()==""){
            return Result.error("请填写密码");
        }
        if(user.getEmail()==null||user.getUsername()==""){
            return Result.error("请输入邮箱");
        }
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        QueryWrapper<User> phoneQuery = new QueryWrapper<>();
        QueryWrapper<User> emailQuery = new QueryWrapper<>();
        /*
        用户名、电话、邮箱通过逻辑实现不可重复
         */
        usernameQuery.eq("username",user.getUsername());
        phoneQuery.eq("phone",user.getPhone());
        emailQuery.eq("email",user.getEmail());


        usernameQuery.eq("is_delete",0);
        phoneQuery.eq("is_delete",0);
        emailQuery.eq("is_delete",0);
        User checkUsername = userService.getOne(usernameQuery);
        if(checkUsername != null){
            return Result.error(CodeError.USERNAME_ALREADY,"该用户名已经存在");
        }
        User checkPhone = userService.getOne(phoneQuery);
        if(checkPhone != null){
            return Result.error(CodeError.USER_PHONE_ALREADY,"该电话号码已经绑定了账号");
        }
        User checkEmail = userService.getOne(emailQuery);
        if(checkEmail!=null){
            return Result.error(CodeError.USER_EMAIL_ALREADY,"该电子邮箱已被使用");
        }
        boolean isSave;

        isSave=userService.saveOrUpdate(user);
        if(isSave){
            /*
            若没传入角色id，则数据库默认为普通用户
             */
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(user.getRoleId());
            UserRoleService.save(userRole);
            return Result.success("新增操作成功");
        } else{
            return Result.error(CodeError.USER_INSERT_FAIL,"新增操作失败");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result changePassword(String email,String password){
        if(email!=null){
            QueryWrapper<User> EmailqueryWrapper = new QueryWrapper<>();
            EmailqueryWrapper.eq("email",email);
            EmailqueryWrapper.eq("is_delete",0);
            User user = userService.getOne(EmailqueryWrapper);
            user.setPassword(password);
            boolean isChange = userService.saveOrUpdate(user);
            if(isChange){
                return Result.success("修改成功");
            }else{
                return Result.error("修改失败");
            }
        }else{
            return Result.error("邮箱参数错误");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateUser(User user){
        //判断用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("is_delete",0);
        User checkUsername = userService.getOne(queryWrapper);
        if(checkUsername != null&&checkUsername.getId()!=user.getId()){
            return Result.error(CodeError.USERNAME_ALREADY,"该用户名已经被别人取了！");
        }

        //判断邮箱是否重复
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("email",user.getEmail());
        queryWrapper1.eq("is_delete",0);
        User checkUsername1 = userService.getOne(queryWrapper1);
        if(checkUsername1 != null&&checkUsername1.getId()!=user.getId()){
            return Result.error("该邮箱已绑定用户！");
        }


        if(user.getBirthday()!=null){
           Integer age = birthdayService.CalculationAge(user.getBirthday());
           user.setAge(age);
        }


        boolean isUpdate;
        isUpdate=userService.saveOrUpdate(user);
        if(isUpdate){
            if(user.getRoleId()!=null){
                QueryWrapper<UserRole> roleQuery = new QueryWrapper<>();
                roleQuery.eq("user_id",user.getId());
                UserRole userRole = UserRoleService.getOne(roleQuery);
                userRole.setRoleId(user.getRoleId());
                UserRoleService.updateById(userRole);
            }

            return Result.success("修改操作成功");
        } else{
            return Result.error(CodeError.USER_MOD_FAIL,"修改操作失败");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result userList(Integer currentPage){
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("is_delete",0);
        Page page = new Page(currentPage, Pagesize.pageSize1);
        IPage<User> users=userService.page(page,query);
        if (users!=null){
            for(User user : users.getRecords()){
                QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",user.getId());
                Long roleId = (UserRoleService.getOne(queryWrapper)).getRoleId();
                String roleName= roleService.getById(roleId).getRoleName();
                user.setRole(roleName!=null?roleName:"用户角色丢失了，😭");
                if(user.getSex()!=null){
                    user.setSexText(tDictService.getDictText(user.getSex(),"hotelSex"));
                }
            }
            return Result.success("用户列表获取成功",users);
        }else {
            return Result.error(CodeError.USER_LIST_NULL,"没有找到用户列表");
        }
    }

    @Override
    @Transactional
    public User selectById(Long userId){
        User user = userService.getById(userId);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<User> getList(){
        QueryWrapper<User> q1 = new QueryWrapper<>();
        q1.eq("is_delete",0);
        List<User> users = userService.list(q1);
        if (users!=null){
            for(User user : users){
                QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",user.getId());
                Long roleId = (UserRoleService.getOne(queryWrapper)).getRoleId();
                user.setRole(roleService.getById(roleId).getRoleName());
                this.getSexText(user);
            }
            return users;
        }else {
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result ExportExcelUserList(HttpServletResponse response){
        List<User> users = userService.getList();
        if(users != null && users.size() > 0) {
            for(User user :users){
                this.getSexText(user);
                user.setPassword("********");
            }
            try{
                ExcelUtils.exportExcel(users, null, "用户数据", User.class, "用户信息.xlsx", response);
            }catch (Exception e){
                return Result.error(CodeError.INTERNAL_EXCEPTION,"导出失败");
            }
        }
        return Result.success("导出成功");
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result ImportExcelUser(MultipartFile file){
        try{
            List<User> users = ExcelUtils.importData(file, 1, User.class);
            for(User user : users){
                if(user.getPassword()==null||user.getUsername()==null||user.getEmail()==null){
                    return Result.error("存在用户名、密码、邮箱为空的用户");
                }
                if(user.getSexText()!=null){
                    if(user.getSexText().equals("男")){
                        user.setSex(1);
                    }else {
                        user.setSex(0);
                    }
                }
                userService.save(user);
                if(user.getRole()!=null){
                    QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("role_name",user.getRole());
                    Role role = roleService.getOne(queryWrapper);
                    if(role!=null){
                        UserRole ur = new UserRole();
                        ur.setRoleId(role.getId());
                        ur.setUserId(user.getId());
                        UserRoleService.save(ur);
                    }else{
                        UserRole ur = new UserRole();
                        ur.setRoleId(2L);
                        ur.setUserId(user.getId());
                        UserRoleService.save(ur);
                    }
                }else{
                    UserRole ur = new UserRole();
                    ur.setRoleId(2L);
                    ur.setUserId(user.getId());
                    UserRoleService.save(ur);
                }
            }
            System.out.println(users);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success("导入成功");
    }

    @Override
    public ModelAndView ExportUserPdf(User user){
        try {
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",user.getId());
            Long roleId = (UserRoleService.getOne(queryWrapper)).getRoleId();
            user.setRole(roleService.getById(roleId).getRoleName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            if(user.getAvatar()==null){
                user.setAvatar("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2630270280,153221653&fm=26&gp=0.jpg");
            }
            Product product = new Product("头像",user.getAvatar());
            Product product1 = new Product("用户编号", String.valueOf(user.getId()));
            Product product2 = new Product("姓名",user.getUsername());
            Product product3 = new Product("注册时间",sdf.format(user.getCreateTime()));
            Product product5 = new Product("年龄",String.valueOf(user.getAge()));
            Product product6 = new Product("邮箱",user.getEmail());
            Product product7 = new Product("联系方式",user.getPhone());
            Product product8 = new Product("身份证号码",user.getIdcard());
            Product product9 = new Product("担任角色",String.valueOf(user.getRole()));
            List<Product> products = new ArrayList<>();
            products.add(product);
            products.add(product1);
            products.add(product2);
            products.add(product3);
            products.add(product5);
            products.add(product6);
            products.add(product7);
            products.add(product8);
            products.add(product9);
            Map<String, Object> model = new HashMap<>();
            model.put("sheet", products);
            return new ModelAndView(new ViewPDF(), model);
        }catch (Exception e){
            return new ModelAndView(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<User> SearchUser(UserSearchVO vo){
        Integer currentPage = vo.getCurrentPage();
        if(currentPage==null){
            currentPage = 1;
        }
        User user = new User();
        BeanUtils.copyProperties(vo,user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(user.getUsername()!=""&&user.getUsername()!=null){
            queryWrapper.like("username",user.getUsername());
        }
        if(user.getIdcard()!=null){
            queryWrapper.like("idcard",user.getIdcard());
        }

        if(user.getAge()!=null){
            queryWrapper.like("age",user.getAge());
        }

        if(user.getPhone()!=""&&user.getPhone()!=null){
            queryWrapper.like("phone",user.getPhone());
        }
        if(user.getEmail()!=""&&user.getEmail()!=null){
            queryWrapper.like("email",user.getEmail());
        }
        queryWrapper.eq("is_delete",0);
        Page page = new Page(currentPage, Pagesize.pageSize1);
        IPage<User> users=userService.page(page,queryWrapper);
        for(User item : users.getRecords()){
            if(item.getSex()!=null){
                item.setSexText(tDictService.getDictText(item.getSex(),"hotelSex"));
            }
        }
        return users;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User GetUserView(Long id){
        User user = userService.getById(id);
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        Long roleId = (UserRoleService.getOne(queryWrapper)).getRoleId();
        user.setPassword(null);
        user.setRole(roleService.getById(roleId).getRoleName());
        user.setRoleId(roleId);
        this.getSexText(user);
        return user;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result UserUploadImg(MultipartFile file){
        if (!file.isEmpty()) {
            //对文文件的全名进行截取然后在后缀名进行删选。
            int begin = file.getOriginalFilename().indexOf(".");
            int last = file.getOriginalFilename().length();
            //获得文件后缀名
            String a = file.getOriginalFilename().substring(begin, last);
            //判断是否为图片
            if ((".gif").equals(a)||(".GIF").equals(a)||
                    (".jpg").equals(a)||(".JPG").equals(a)||
                    (".PNG").equals(a)||(".png").equals(a)){
                //这里是正确的图片格式
                String fileName;

                fileName = file.getOriginalFilename();
                fileName= UUIDGenrateUtil.generateShortUuid() +"_"+fileName;
                String dirPath ="/www/server/tomcat/webapps/user/image/";
                File filePath = new File(dirPath);

                if(!filePath.exists()){
                    filePath.mkdirs();
                }
                try{
//
                    file.transferTo((new File(dirPath+fileName)));

                    String encoderUrl = URLEncoder.encode(fileName, "UTF-8");
                    String fileurl="http://" + Server.iphost+":"+Server.port+ "/user/image/"+encoderUrl;
                    return Result.success("头像上传成功！！",fileurl);
                }catch (Exception e){
                    e.printStackTrace();
                    return Result.error(CodeError.INTERNAL_EXCEPTION,"出现异常");
                }
            }else {
                return Result.error("请上传png、jpg格式的图片");
            }
        }else {
            return Result.error("该文件为空文件");
        }



    }
}
